"use strict";

GameUI.SetCameraTerrainAdjustmentEnabled( false );
var trade_data = {};
var pm_data = {};
var left_id = -1;
var right_id = -1;
function localHiddenMsg(){
	$('#errorMsgBG').SetHasClass("AniScaleOut",false);
	$('#errorMsgBG').SetHasClass("Hidden",true);
}
function localShowMsg(){
	$('#errorMsgBG').SetHasClass("AniScaleOut",true);
	$('#errorMsgBG').SetHasClass("Hidden",false);
}

function formatString(str,args){
	for(var i in args){
		var arg = args[i];
		str = str.replace("s"+i,arg);
	}
	return str;
}
var g_func_hiddenClass = null;
function onErrorMsg(data){
	var text = data.text
	var errorMsgBG = $('#errorMsgBG');
	Game.EmitSound( "General.CastFail_AbilityNotLearned" );
	if (errorMsgBG.BHasClass("AniScaleOut")){
		localHiddenMsg();
		$.CancelScheduled(g_func_hiddenClass);
	}
	localShowMsg();
	$('#errorMsgTxt').text = $.Localize(text);
	g_func_hiddenClass = $.Schedule(1.2,localHiddenMsg);
}
GameUI.onErrorMsg = onErrorMsg;
GameEvents.Subscribe( "S2C_ERROR_MSG", onErrorMsg );
localHiddenMsg();

function animateScale(panel){
	if (panel.visible==false) {
		panel.AddClass("AniScaleOut");
		panel.RemoveClass("AniScaleIn");
		panel.style.visibility = 'visible';
		//$('#QuestRoot').AddClass("RootHeight");

	}else{
		panel.RemoveClass("AniScaleOut");
		panel.AddClass("AniScaleIn");
		$.Schedule(0.2,function () {
			//$('#QuestRoot').RemoveClass("RootHeight");
			panel.style.visibility = 'collapse';
		});
	}
}

function BTN_ADD_GOLD(side){
	var localid = Game.GetLocalPlayerID();
	if (side == 1){
		if(localid == left_id){
			var gold = $('#inputTradeLeft').text;
			if (isNaN(gold)){
				return;
			}
			gold = Math.floor(gold);
			GameEvents.SendCustomGameEventToServer( "C2S_PUSH_GOODS", {gold:gold,owner:localid} );
		}
	}else if (side == 2){
		if(localid == right_id){
			var gold = $('#inputTradeRight').text;
			if (isNaN(gold)){
				return;
			}
			gold = Math.floor(gold);
			GameEvents.SendCustomGameEventToServer( "C2S_PUSH_GOODS", {gold:gold,owner:localid} );
		}
	}

}

function BTN_SURE_TRADE(){
	GameEvents.SendCustomGameEventToServer( "C2S_COMPLETE_TRADE", {} );
}
function BTN_CANCLE_TRADE(){
	//清空交易区的数据
	GameEvents.SendCustomGameEventToServer( "C2S_CANCLE_TRADE", {} );
}
var pm_info_idx = 0;
var pm_info_gold = 0;
var pm_info_curid = -1;
function add_pm_info(data){
	var name = Players.GetPlayerName( data.id );
	var str = name + $.Localize('#CHUJIA') + data.gold;
	var panel = $.CreatePanel("Panel", $('#right_paimai_content'), "pm_info" + pm_info_idx);
	pm_info_idx++;
	panel.BLoadLayoutSnippet("pmcell");
	var lb = panel.FindChildTraverse("pmlb");
	lb.text = str;
	$('#right_paimai_content').ScrollToBottom();
}

function BTN_SURE_PM(){
	var gold = $('#inputGold').text;
	if (isNaN(gold)){
		GameUI.onErrorMsg({text:"TIP_PMGOLD"});
		return;
	}
	gold = Math.floor(gold);
	var localid = Players.GetLocalPlayer();
	if (localid!=pm_info_curid) {
		GameUI.onErrorMsg({text:"TIP_NOT_YOUR_TURN"});
		return;
	}
	GameEvents.SendCustomGameEventToServer( "C2S_PAIMAI", {gold:gold} );
}

function BTN_CANCLE_PM(){
	var localid = Players.GetLocalPlayer();
	if (localid!=pm_info_curid) {
		GameUI.onErrorMsg({text:"TIP_NOT_YOUR_TURN"});
		return;
	}
	GameEvents.SendCustomGameEventToServer( "C2S_PAIMAI_GIVEUP", {} );
}

function BTN_SHOWINFO(){
	animateScale($('#InfoPanel'));
}
//屏蔽当前空白地方点击
function ShieldScreen(){

}

function OnSubmitted(){
	$.Msg("submit");
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
function C2S_GET_PLAYER_DATA(data){
	var data1 = null;
	var data2 = null;
	var id = Game.GetLocalPlayerID();
	if (id == data.p1.id) {
		data1 = data.p1;
		data2 = data.p2;

	}else{
		data1 = data.p2;
		data2 = data.p1;
	}
	
}

//物品从左边移到右边
function C2S_PUSH_GOODS(data){
	if (data.gold>0){
		if (data.owner == left_id){
			$('#goldLabelLeft').text = data.itemIndex;
			$('#btn_addgoldLeft').visible = false;
		}else{
			$('#goldLabelRight').text = data.itemIndex;
			$('#btn_addgoldRight').visible = false;
		}
		
	}else{
		var pname = '#city'+data.itemIndex;
		var panel = $(pname);
		var name = panel.GetItemName();

		//从左栏移除
		$('#city'+data.itemIndex).RemoveAndDeleteChildren()
		$('#city'+data.itemIndex).DeleteAsync(0);
		var panel = null;
		if (data.owner==left_id){
			//添加到右栏
			panel = $.CreatePanel("Panel", $('#lc_trade'), pname);
		}else{
			panel = $.CreatePanel("Panel", $('#rc_trade'), pname);
		}
		panel.BLoadLayout( "file://{resources}/layout/custom_game/ItemNode.xml", false, false );
		panel.SetItemIndex(data.itemIndex);
		panel.SetItemName(name);
		panel.SetItemType(false);
		panel.SetItemOwner(data.owner);
	}
}

function C2S_POP_GOODS(data){
	
}
function C2S_COMPLETE_TRADE(data){
	C2S_CANCLE_TRADE(data);
}
function C2S_REQUEST_TRADE(data){
	$('#left_trade').RemoveAndDeleteChildren();
	$('#right_trade').RemoveAndDeleteChildren();
	$('#lc_trade').RemoveAndDeleteChildren();
	$('#rc_trade').RemoveAndDeleteChildren();
	$('#goldLabelLeft').text = "0";
	$('#goldLabelRight').text = "0";
	$('#inputTradeLeft').text = "";
	$('#inputTradeRight').text = "";
	$('#btn_addgoldLeft').visible = true;
	$('#btn_addgoldRight').visible = true;
	$('#TradePanel').visible = true;
	trade_data = data;
	var caster_data = data.p1;
	var target_data = data.p2;
	left_id = data.id1;
	right_id = data.id2;
	$('#playerName1').text = Players.GetPlayerName( left_id );
	$('#playerName2').text = Players.GetPlayerName( right_id );
	for(var i in caster_data){
		var city = caster_data[i];
		var panel = $.CreatePanel("Panel", $('#left_trade'), "city"+city.city);
		panel.BLoadLayout( "file://{resources}/layout/custom_game/ItemNode.xml", false, false );
		panel.SetItemIndex(city.city);
		panel.SetItemName(city.name);
		panel.SetItemType(true);
		panel.SetItemOwner(left_id);
	}
	for(var i in target_data){
		var city = target_data[i];
		var panel = $.CreatePanel("Panel", $('#right_trade'), "city"+city.city);
		panel.BLoadLayout( "file://{resources}/layout/custom_game/ItemNode.xml", false, false );
		panel.SetItemIndex(city.city);
		panel.SetItemName(city.name);
		panel.SetItemType(true);
		panel.SetItemOwner(right_id);
	}
}
function C2S_CANCLE_TRADE(data){
	$('#TradePanel').visible = false;
}
function C2S_PAIMAI(data){
	pm_info_curid = data.nextid;
	pm_info_gold = data.gold;
	var localid = Players.GetLocalPlayer();
	if(localid != pm_info_curid) {
		$('#btn_pm').enable = false;
		$('#btn_pm_cancle').enable = false;
	}
	add_pm_info(data);
}
// function get_game_state(){
// 	GameEvents.SendCustomGameEventToServer( "C2S_GET_GAME_STATE", {} );
// }
// function C2S_GET_GAME_STATE(data){

// }
//请求打开拍卖界面  其实是服务器端通知的，现在用来测试
function S2C_REQUEST_PAIMAI(data){
	//$.Msg(data);
	var lvdesc = data.lvdesc || "LEVEL";
	pm_data = data;
	$('#right_paimai_content').RemoveAndDeleteChildren();
	$("#modelPanel").RemoveAndDeleteChildren();
	$('#pm_lv').RemoveAndDeleteChildren();
	$('#PaimaiPanel').visible = true;
	var sceneContainer = $("#modelPanel");
	var style = "width:200px;height:400px;";
	var hero = data.cityinfo.entindex;
	var name = data.citydata.name;
	//sceneContainer.BCreateChildren("<DOTAScenePanel style='" + style + "' unit='" + name + "' particleonly='false' rotateonhover='true' yawmin='-10' yawmax='10' pitchmin='-10' pitchmax='10'/>");

	$('#lb_name').text = $.Localize('#'+name);
	var attrs = data.citydata.build;
	if (data.citydata.chezhan!=undefined){
		attrs = data.citydata.chezhan;
	}
	var ostr = $.Localize('#'+lvdesc);
	    
	for(var i in attrs){
		var panel = $.CreatePanel("Panel", $('#pm_lv'), "pm_lv"+i);
	    panel.BLoadLayoutSnippet("pmcell");
	    var lb = panel.FindChildTraverse("pmlb");
	    var ss = formatString(ostr,["",i,attrs[i]]);
		lb.text =  ss;
	}
	var redir = {id:data.cityinfo.owner};
	S2C_PAIMAI_CHANGE_PLAYER(redir);
}
function C2S_PAIMAI_END(data){
	$("#modelPanel").RemoveAndDeleteChildren();
	$('#pm_lv').RemoveAndDeleteChildren();
	$('#PaimaiPanel').visible = false;
}

function C2S_PAIMAI_GIVEUP(data){
	var localid = Players.GetLocalPlayer();
	if(localid == data.id){
		$('#btn_pm').enable = false;
		$('#btn_pm_cancle').enable = false;
	}
	add_pm_info(data);
}
function S2C_PAIMAI_CHANGE_PLAYER(data){
	var curid = data.id;
	pm_info_curid = curid;
	var myid = Players.GetLocalPlayer();
	if (curid == myid) {
		$('#btn_pm').enable = true;
		$('#btn_pm_cancle').enable = true;
	}else{
		$('#btn_pm').enable = false;
		$('#btn_pm_cancle').enable = false;
	}
}
function C2S_GET_PM_DATA(data){
	
}
function C2S_DIYA(data){
	
}
function C2S_BUILD(data){
	
}
function C2S_SELL(data){
	
}

function C2S_GET_TRADING_DATA(data){
	
}

//重连的暂时不做了，没有精力
//S2C_REQUEST_PAIMAI();
GameEvents.Subscribe( "C2S_GET_PLAYER_DATA", C2S_GET_PLAYER_DATA );
GameEvents.Subscribe( "C2S_PUSH_GOODS", C2S_PUSH_GOODS );
GameEvents.Subscribe( "C2S_POP_GOODS", C2S_POP_GOODS );
GameEvents.Subscribe( "C2S_COMPLETE_TRADE", C2S_COMPLETE_TRADE );
GameEvents.Subscribe( "C2S_REQUEST_TRADE", C2S_REQUEST_TRADE );
GameEvents.Subscribe( "C2S_CANCLE_TRADE", C2S_CANCLE_TRADE );
GameEvents.Subscribe( "C2S_PAIMAI", C2S_PAIMAI );
GameEvents.Subscribe( "C2S_PAIMAI_END", C2S_PAIMAI_END );
GameEvents.Subscribe( "C2S_PAIMAI_GIVEUP", C2S_PAIMAI_GIVEUP );
GameEvents.Subscribe( "C2S_DIYA", C2S_DIYA );
GameEvents.Subscribe( "C2S_BUILD", C2S_BUILD );
GameEvents.Subscribe( "C2S_SELL", C2S_SELL );
GameEvents.Subscribe( "C2S_GET_PM_DATA", C2S_GET_PM_DATA );
GameEvents.Subscribe( "C2S_GET_TRADING_DATA", C2S_GET_TRADING_DATA );



////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
function S2C_CREATE_PLAYER_INFO(data){
	$('#InfoPanel').RemoveAndDeleteChildren();
	var infos = data.infos;
	for(var i in infos){
		var info = infos[i];
		var panel = $.CreatePanel("Panel", $('#InfoPanel'), "player" + info.playerid);
	    panel.BLoadLayoutSnippet("infocell");
	}
	S2C_UPDATE_PLAYER_INFO(data);
}

function S2C_UPDATE_PLAYER_INFO(data){
	$.Msg(data);
	var infos = data.infos;
	for (var i in infos){
		var info = infos[i];
		var steamid = info.steamid;
		var panel = $('#player'+info.playerid);
		var avatar = panel.FindChildTraverse("avatar");
		var name = panel.FindChildTraverse("name");
		var gold = panel.FindChildTraverse("gold");
		if (steamid!=undefined){
			avatar.steamid = steamid;
			name.steamid = steamid;
		}
		if (info.gold!=undefined){
			gold.text = info.gold;
		}
		
		var cityPanel = panel.FindChildTraverse("CityPanel");
		//for test
		// info.cities = [{itemName:"tuerqi",itemIndex:"1001"
		// },{itemName:"tuerqi",itemIndex:"1002"},{itemName:"tuerqi",itemIndex:"1001"
		// },{itemName:"faguo",itemIndex:"1002"}];
		//for test
		if (info.cities!=undefined) {
			cityPanel.RemoveAndDeleteChildren();
		}
		for (var j in info.cities){
			var city = info.cities[j];
			var panel = $.CreatePanel("Panel", cityPanel, "infocity"+city.city);
			panel.BLoadLayout( "file://{resources}/layout/custom_game/ItemNode.xml", false, false );
			panel.SetItemIndex(city.city);
			panel.SetItemName(city.name);
			panel.SetItemType(false);
		}
	}
}
//改变当前玩家
function S2C_CHANGE_PLAYER(data){
	
	//改变info栏的高亮
	var playerid = data.playerid;
	for(var i=0;i<10;i++){
		if (Players.IsValidPlayerID( i )){
			$('#player'+i).SetHasClass("Highlight",i == playerid);
		}
	}
	
}

function S2C_PLAYER_FAIL(data){
	//改变info栏的高亮
	var playerid = data.id;
	$('#player'+playerid).SetHasClass("Highlight",false);
	$('#player'+playerid).SetHasClass("PlayerFail",true);

}

//倒计时的更改
function S2C_CHANGE_TIME(data){
	var left = data.total - data.cur;
	$('#TimerLabel').text = left;
	$('#TimerBar').style.width = left / data.total * 100 + "%";
	// if(left == 0){
	// 	$('#TimerLabel').visible = false;
	// }else{
	// 	$('#TimerLabel').visible = true;
	// }
	if (data.isStart != 0){
		if (data.str == undefined) {
			data.str = "";
		}
		if (data.args == undefined) {
			data.args = [];
		}
		var str = formatString($.Localize(data.str),data.args);
		$('#TimerLabelTip').text = str;
	}
}
function S2C_SHOW_RANDOM_EVENT(data){
	var panel = $('#EventPanel');
	var lb = panel.FindChildTraverse("EventLabel");
	var str = formatString($.Localize(data.str),data.args);
	lb.text = str;
	
	if (panel.visible == true) {
		panel.visible = false;
	}
	
	animateScale(panel);
	$.Schedule(2,function(){
		var panel2 = $('#EventPanel');
		animateScale(panel2);
	});
}
function S2C_CITY_DIYA(data){
	var panel = $('#infocity'+data.itemIndex);
	panel.SetHasClass("DiYa",data.opt == 1);
}

GameEvents.Subscribe( "C2S_REQUEST_PAIMAI", S2C_REQUEST_PAIMAI );
GameEvents.Subscribe( "S2C_CREATE_PLAYER_INFO", S2C_CREATE_PLAYER_INFO );
GameEvents.Subscribe( "S2C_UPDATE_PLAYER_INFO", S2C_UPDATE_PLAYER_INFO );
GameEvents.Subscribe( "S2C_CHANGE_PLAYER", S2C_CHANGE_PLAYER );
GameEvents.Subscribe( "S2C_CHANGE_TIME", S2C_CHANGE_TIME );
GameEvents.Subscribe( "S2C_PAIMAI_CHANGE_PLAYER", S2C_PAIMAI_CHANGE_PLAYER );
GameEvents.Subscribe( "S2C_SHOW_RANDOM_EVENT", S2C_SHOW_RANDOM_EVENT );
GameEvents.Subscribe( "S2C_CITY_DIYA", S2C_CITY_DIYA );
//这个无法获取没有hitbox的单位
function GetMouseTarget()
{
    var mouseEntities = GameUI.FindScreenEntities( GameUI.GetCursorPosition() )
    var localHeroIndex = Players.GetPlayerHeroEntityIndex( Players.GetLocalPlayer() )
    for ( var e of mouseEntities )
    {
        if ( !e.accurateCollision )
            continue
        var name = Entities.GetUnitName( e.entityIndex );
        if (name == "npc_block")
        	return e.entityIndex
    }

    for ( var e of mouseEntities )
    {
    	var name = Entities.GetUnitName( e.entityIndex );
        if (name == "npc_block")
        	return e.entityIndex
    }

    return 0
}



function getCityData(){
	var _pos = GameUI.GetScreenWorldPosition( GameUI.GetCursorPosition() );
	if (_pos!=null){
		GameEvents.SendCustomGameEventToServer( "C2S_GET_CITY_DATA", {pos:_pos} );
	}
}
var timer_cityinfopanel = null;
function C2S_GET_CITY_DATA(data){
	$('#CityLvPanel').RemoveAndDeleteChildren();
	var name = data.name;
	var gold = data.gold || "???";
	var lv = data.lv;
	var lvdesc = data.lvdesc || "LEVEL";
	var owner = data.owner;
	if (owner!=undefined){
		$('#CityOwner').visible = true;
		$('#CityOwner').heroname = Players.GetPlayerName( owner );
	}else{
		$('#CityOwner').visible = false;
	}
	if($('#CityInfoPanel').visible == false){
		animateScale($('#CityInfoPanel'));
	}
	
	$('#CityNameAndGold').text = $.Localize("#"+name) + " [$"+gold+"] ";

	var attrs = data.build;
	if (data.chezhan!=undefined){
		attrs = data.chezhan;
	}
	var ostr = $.Localize('#'+lvdesc);

	for(var i in attrs){
		var panel = $.CreatePanel("Panel", $('#CityLvPanel'), "citylv" + i);
		panel.BLoadLayoutSnippet("citylv");
		var lb = panel.FindChildTraverse("lb_citylv");
		var ss = formatString(ostr,["",i,attrs[i]]);
		lb.text = ss;
	}
}
GameEvents.Subscribe( "C2S_GET_CITY_DATA", C2S_GET_CITY_DATA );

GameUI.SetMouseCallback( function( eventName, arg ) {
    var CONSUME_EVENT = true
    var CONTINUE_PROCESSING_EVENT = false
    var LEFT_CLICK = (arg === 0)
    var RIGHT_CLICK = (arg === 1)

    if ( GameUI.GetClickBehaviors() !== CLICK_BEHAVIORS.DOTA_CLICK_BEHAVIOR_NONE )
        return CONTINUE_PROCESSING_EVENT

    if ( eventName === "pressed" || eventName === "doublepressed")
    {
        if (LEFT_CLICK) 
        {
        	
		    getCityData();
        	return true;
        }
    }
    return CONTINUE_PROCESSING_EVENT
} );
function BTN_CLOSE_CITYINFO(){
	animateScale($('#CityInfoPanel'));
	
}

function S2C_CAMERA_CHANGE(data){
	var dis = data.dis;
	GameUI.SetCameraDistance(dis);
}

GameEvents.Subscribe( "S2C_CAMERA_CHANGE", S2C_CAMERA_CHANGE );

function S2C_SHOW_CHOICE(data){
	var lvdesc = data.lvdesc || "LEVEL";
	var citydata = data.citydata;
	if (citydata.gold == undefined || citydata.gold <= 0){
		$('#btn_buy').visible = false;
	}else{
		$('#btn_buy').visible = true;
	}
	$('#ChoicePanel').visible = true;
	$('#choice_lv').RemoveAndDeleteChildren();
	$('#choice_cityname').text = $.Localize("#"+citydata.name);
	var attrs = citydata.build;
	if (citydata.chezhan!=undefined){
		attrs = citydata.chezhan;
	}
	var ostr = $.Localize('#'+lvdesc);
	for(var i in attrs){
		var panel = $.CreatePanel("Panel", $('#choice_lv'), "choice_lv"+i);
	    panel.BLoadLayoutSnippet("pmcell");
	    var lb = panel.FindChildTraverse("pmlb");
	    var ss = formatString(ostr,["",i,attrs[i]]);
		lb.text =  ss;
	}
	$('#ChoicePanel').SetAttributeInt("cityid", citydata.city);
	$('#ChoicePanel').SetAttributeInt("curid", data.curid);
}

function S2C_CHOICE_DONE(data){
	$('#ChoicePanel').visible = false;
}
//todo 在重连的时候要处理一下Attr
function BTN_CHOICE(opt){
	var curid = $('#ChoicePanel').GetAttributeInt("curid", -1);
	var localid = Game.GetLocalPlayerID();
	if (curid == localid){
		GameEvents.SendCustomGameEventToServer("S2C_CHOICE_DONE",{opt:opt,cityid:$('#ChoicePanel').GetAttributeInt("cityid", 1)});
	}
}
function BTN_GIVEUP(){
	GameEvents.SendCustomGameEventToServer("C2S_GIVEUPGAME",{});
}

function BTN_SHOWGIVEUP(){
	$('#GiveupPanel').visible = true;
}
function BTN_GIVEUP_CANCLE(){
	$('#GiveupPanel').visible = false;
}

GameEvents.Subscribe( "S2C_SHOW_CHOICE", S2C_SHOW_CHOICE );
GameEvents.Subscribe( "S2C_CHOICE_DONE", S2C_CHOICE_DONE );
GameEvents.Subscribe( "S2C_PLAYER_FAIL", S2C_PLAYER_FAIL );
var unitNames = {};
var NPCTaskList = [];
var NPCTaskLabels = {};
var m_WidthOffset = 125;
var m_LastTime = -1;
var height = 0;
function C2S_GET_UNITNAME(){
	GameEvents.SendCustomGameEventToServer("C2S_GET_UNITNAME",{});
}
function UpdateUnitName(){
	var lastTimeout = Game.Time() >= m_LastTime;
	if (lastTimeout) m_LastTime = Game.Time() + 0.6;

	var len = NPCTaskList.length;
	for (var i = 0; i < len; i++) {
		var entIndex = NPCTaskList[i];
		var main = NPCTaskLabels[entIndex];
		if( !main.IsValid() )return;

		var origin = Entities.GetAbsOrigin(parseInt(entIndex));
		var pos = [Game.WorldToScreenX(origin[0],origin[1],origin[2]),Game.WorldToScreenY(origin[0],origin[1],origin[2])];

		var w = Game.GetScreenWidth();
		var h = Game.GetScreenHeight();

		if( pos[0] > w || pos[0] < 0 || pos[1] > h || pos[1] < 0 || Entities.IsOutOfGame(entIndex) )
			main.visible = false;
		else {
			if (lastTimeout) {
				// SetTopPanel(main, entIndex);
				// SetOresPoints(main, entIndex);
			}

			var maxwidth = (w/h)*1080;
			var midwidth = maxwidth/2;
			var newX = ((pos[0] / w) * maxwidth) - main.actuallayoutwidth / 2;
			var newY = ((pos[1] / h) * 1080) - height - main.actuallayoutheight/2;

			if (newX>midwidth) {
				newX += ((newX-midwidth)/midwidth)*m_WidthOffset;
			}
			else{
				newX -= ((midwidth-newX)/midwidth)*m_WidthOffset;
			}

			if (newY>540) {
				newY -= ((540-newY)/540)*50;
			}
			else{
				newY += ((newY-540)/540)*50;
			}

			var newPos = newX + "px " + newY + "px 0px";
	        main.style["position"] = newPos;
			main.visible = true;
		}
	}

	$.Schedule(0.01,UpdateUnitName);
}
function S2C_GET_UNITNAME(unitNames){
	unitNames = unitNames || {};
	var hasData = false;
	for(var idx in unitNames){
		var v = unitNames[idx];
		var entindex = Number(idx);
		var main = $.CreatePanel("Panel",$('#CityNamePanel'),v);
		main.BLoadLayoutSnippet("cityname")
		main.visible = false;
		//main.AddClass("npc-task");

		var label = main.FindChildTraverse("lb_cityname");
		label.text = $.Localize("#"+v);
		NPCTaskLabels[entindex] = main;
		NPCTaskList.push(entindex);
		hasData = true;
	}
	if (!hasData){
		$.Schedule(1,C2S_GET_UNITNAME);
	}else{
		UpdateUnitName();
	}
}
C2S_GET_UNITNAME();
GameEvents.Subscribe( "S2C_GET_UNITNAME", S2C_GET_UNITNAME );
function isInteger(obj) {
 return Math.floor(obj) === obj
}
function C2S_GET_TURNTABLE(){
	GameEvents.SendCustomGameEventToServer("C2S_GET_TURNTABLE",{});
}
var turn_table_length = -1;
var turn_count = -1;
function TURN_TABLE(idx,target){
	Game.EmitSound("lina_game_peg_hit_metal"); 
	if(idx>turn_table_length){
		idx = 1;
	}

	if (idx == 1){
		turn_count ++;
	}
	for(var i=1;i<=turn_table_length;i++){
		$('#element'+i).SetHasClass("Highlight",i==idx);
	}
	if (turn_count>=3 && idx == target){
		Game.EmitSound("lina_game_goal6"); 
		return;
	}
	$.Schedule(0.03+(turn_count-1)*0.05,function(){
			TURN_TABLE(idx+1,target);
		});
}

function S2C_TURNTABLE(data){
	$('#TurntablePanel').visible = true;
	var dest = data.dest;
	turn_count = 0;
	TURN_TABLE(1,dest);
}

//前提是总数为偶数
function S2C_GET_TURNTABLE(data){

	$('#TurntablePanel').RemoveAndDeleteChildren();
	var length = data.length;
	var width = $('#TurntablePanel').actuallayoutwidth;
	var height = $('#TurntablePanel').actuallayoutheight;

	var x,y,t;
	turn_table_length = length;
	t = length;
	y = x;
	//x = t/2 - (y-2);
	x = t/4 + 1;
	if (!isInteger(x)){
		x = Math.floor(t / 4 + 3 / 2);
		y = x - 1;
	}
	var startx = width / 2;
	startx = startx - 60 * x + 60 ;
	
	var starty = height / 2;
	starty = starty - 60 * y + 60;

	//top  1-4
	for(var i=1;i<=x;i++){
		var element = $.CreatePanel("Panel",$('#TurntablePanel'),"element"+i);
		element.BLoadLayoutSnippet("tt_element")
		var label = element.FindChildTraverse("lb_tt_element");
		label.text = $.Localize(data.elements[i]);
		var pos_style = ((i-1)*120+startx) + "px " + starty + "px 0px";
		element.style.position = pos_style;
	}
	startx = (x-1) * 120 + startx;
	//midright  5 - 6
	for(var i=x+1;i<=x+y-1;i++){
		var element = $.CreatePanel("Panel",$('#TurntablePanel'),"element"+i);
		element.BLoadLayoutSnippet("tt_element")
		var label = element.FindChildTraverse("lb_tt_element");
		label.text = $.Localize(data.elements[i]);
		var pos_style = startx + "px " + ((i-x)*120+starty) + "px 0px";
		element.style.position = pos_style;
	}
	starty = (x+y-x-1) * 120 + starty;
	//bottom  7 - 9
	for(var i=x+y;i<=2*x+y-2;i++){
		var element = $.CreatePanel("Panel",$('#TurntablePanel'),"element"+i);
		element.BLoadLayoutSnippet("tt_element")
		var label = element.FindChildTraverse("lb_tt_element");
		label.text = $.Localize(data.elements[i]);
		var pos_style = (startx-(i-x-y+1)*120) + "px " + starty + "px 0px";
		element.style.position = pos_style;
	}
	startx = startx-(2*x+y-x-y-1)*120;
	//midleft 10
	for(var i=2*x+y-1;i<=2*x+2*y-4;i++){
		var element = $.CreatePanel("Panel",$('#TurntablePanel'),"element"+i);
		element.BLoadLayoutSnippet("tt_element")
		var label = element.FindChildTraverse("lb_tt_element");
		label.text = $.Localize(data.elements[i]);
		var pos_style = startx + "px " + (starty - (i-2*x-y+2)*120) + "px 0px";
		element.style.position = pos_style;
	}
	starty = starty - (2*x+2*y-2*x-y-5)*120;
	//for test
	//S2C_TURNTABLE({dest:6});
	$('#TurntablePanel').visible = false;
}
function S2C_TURNTABLE_CLOSE(){
	$('#TurntablePanel').visible = false;
}
var g_endData = null;
function S2C_FINISH_GAME(data){
	g_endData = data;
	$('#TimerLabelTip').visible = false;
	$('#TimerBarBg').visible = false;
	$('#GiveupPanel').visible = false;
	//animateScale($('#finishiGamePanel'));
	
}
function getEndData(){
	return g_endData;
}
GameUI.getEndData = getEndData;
GameEvents.Subscribe( "S2C_FINISH_GAME", S2C_FINISH_GAME );
C2S_GET_TURNTABLE();
GameEvents.Subscribe( "S2C_GET_TURNTABLE", S2C_GET_TURNTABLE );
GameEvents.Subscribe( "S2C_TURNTABLE", S2C_TURNTABLE );
GameEvents.Subscribe( "S2C_TURNTABLE_CLOSE", S2C_TURNTABLE_CLOSE );